<template>
  <div class="advertisingSpaceSetting">
    <div class="flex-all pt10 pb10 pl12 pr12 bg-white height50">
      <div class="ct-head-left flex-al">
        <span class="left-line-orange mr10"></span>
        <span class="color-333 fs14">助学助教广告位设置</span>
      </div>
      <div class="cr-head-right">
        <el-button type="primary" size="mini" @click="handAdd">{{
          $t("gradenSet.gradenSet.ReasonForTrial.50zgt2bmc3g0")
        }}</el-button>
      </div>
    </div>
    <div class="pAll12 bt_EBEEF5">
      <div class="tableDiv" ref="auto_height_table">
        <imgTableCont
          :tableData="tableList"
          @handleColumnChange="handleColumnChange"
        >
          <!-- 按钮操作组********start -->
          <el-table-column
            ref="fixedColumn"
            :label="$t('gradenSet.gradenSet.ReasonForTrial.50zgt2bmd1w0')"
            align="center"
            width="120px"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click.native.prevent="handEdit(scope.row)"
                >{{
                  $t("gradenSet.gradenSet.ReasonForTrial.50zgt2bmde40")
                }}</el-button
              >
              <el-button
                type="text"
                size="small"
                @click.native.prevent="handDelete(scope.row)"
                >{{
                  $t("gradenSet.gradenSet.ReasonForTrial.50zgt2bmdpg0")
                }}</el-button
              >
            </template>
          </el-table-column>
          <!-- 按钮操作组********end -->
        </imgTableCont>
        <!-- 分页 -->
        <el-pagination
          style="margin: 10px"
          :current-page.sync="paging.curPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size.sync="paging.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.pageTotal"
          @current-change="curPageChange"
          @size-change="pageSizeChange"
        ></el-pagination>
      </div>
    </div>
    <!-- 侧边弹窗******新增或者编辑学生取消柜询/试听原因 -->
    <el-drawer
      :title="isEdit ? '编辑广告位' : '添加广告位'"
      :visible.sync="cancelVisible"
      direction="rtl"
      size="500px"
      :modal="false"
      custom-class="pop-slider--box"
      :before-close="handleClose"
    >
      <div class="slider-btn">
        <el-button
          v-if="!isEdit"
          type="primary"
          size="mini"
          @click="onSubmit"
          >{{
            $t("gradenSet.gradenSet.ReasonForTrial.50zgt2bme0g0")
          }}</el-button
        >
        <el-button v-else type="primary" size="mini" @click="onEditSubmit">{{
          $t("gradenSet.gradenSet.ReasonForTrial.50zgt2bme0g0")
        }}</el-button>
      </div>
      <div class="slider-content pAll20">
        <el-form
          label-width="120px"
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
        >
          <el-form-item label="图片名称" prop="banner_name">
            <el-input
              clearable
              placeholder="请输入图片名称"
              v-model="ruleForm.banner_name"
              style="width: 320px"
            ></el-input>
          </el-form-item>
          <el-form-item label="广告位图片" prop="banner_imgurl">
            <el-upload
              :limit="1"
              class="avatar-uploader"
              :action="`${gmcApiUrl}/Uploading/Picture`"
              name="ossfile"
              drag
              :data="Uploadeimg"
              :show-file-list="true"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemoveFile"
            >
              <img
                v-if="ruleForm.banner_imgurl"
                :src="ruleForm.banner_imgurl"
                style="width:100%;height:100%"
                alt=""
              />
              <template v-else>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div class="el-upload__tip" slot="tip" style="color:red">
                  图片尺寸为 686*250
                </div>
              </template>
              <el-input
                v-show="false"
                v-model="ruleForm.banner_imgurl"
              ></el-input>
            </el-upload>
          </el-form-item>
          <el-form-item label="排序" prop="banner_sort">
            <el-input
              clearable
              v-model="ruleForm.banner_sort"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              placeholder="请输入排序(数字)"
              style="width: 320px"
            ></el-input>
          </el-form-item>
          <el-form-item label="适用情况" prop="banner_type">
            <el-select
              :disabled="isEdit"
              v-model="ruleForm.banner_type"
              filterable
              clearable
              placeholder="请选择适用园所"
              style="width: 320px"
            >
              <el-option label="全部适配" value="0"></el-option>
              <el-option label="部分适配" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="适用园所"
            prop="school_id"
            v-if="ruleForm.banner_type === '1'"
          >
            <el-select
              v-model="ruleForm.school_id"
              filterable
              multiple
              :disabled="isEdit"
              clearable
              placeholder="请选择适用园所"
              style="width: 320px"
            >
              <el-option
                :label="item.school_cnname"
                :value="item.school_id"
                v-for="(item, index) in schoolList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属模块" prop="banner_class">
            <el-select
              v-model="ruleForm.banner_class"
              filterable
              clearable
              placeholder="请选择所属模块"
              style="width: 320px"
            >
              <el-option label="叮铛助学-家园互动" value="1"></el-option>
              <el-option label="叮铛助学-家园应用" value="2"></el-option>
              <el-option label="叮铛助教-班级圈" value="3"></el-option>
              <el-option label="叮铛助教-园务" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否上架" prop="banner_status">
            <el-select
              v-model="ruleForm.banner_status"
              filterable
              clearable
              placeholder="请选择是否上架"
              style="width: 320px"
            >
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <p class="color-red">
          * {{ $t("gradenSet.gradenSet.ReasonForTrial.50zgt2bmf9s0") }}
        </p>
      </div>
    </el-drawer>
    <!-- 删除取消柜询/试听原因 -->
    <popTips
      :dialogVisable="delItem"
      :popTipsCont="popTips_del"
      @handConfirm="delTeKidBannerAction"
      @handCancel="delItem = false"
      @handleCloseTip="delItem = false"
    ></popTips>

    <div class="small-dialog" v-if="suitParkVisible">
      <el-dialog
        title="适用园所"
        :visible.sync="suitParkVisible"
        width="700px"
        :before-close="handleClose"
      >
        <div class="table-content">
          <imgTableCont :tableData="schoolTableConTent" />
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import imgTableCont from "@/components/tables/imgTableCont.vue";
import popTips from "@/components/common/popTips/popTips.vue";
import setHttp from "../../Set";

export default {
  name: "setting",
  components: {
    imgTableCont,
    popTips,
  },
  data() {
    return {
      schoolList: [],
      gmcApiUrl: "",
      suitParkVisible: false,
      Uploadeimg: {
        company_id: "",
        ossfile: "",
      },
      delItem: false, //删除学生取消柜询/试听原因
      cancelVisible: false, //新增或者编辑职务
      isEdit: false, //是否编辑职务
      banner_id: "",
      currentAd: "",
      //删除学生取消柜询/试听原因****弹窗
      popTips_del: {
        btn_text1: this.$t("gradenSet.gradenSet.ReasonForTrial.50zgt2bmfjw0"),
        btn_text2: this.$t("gradenSet.gradenSet.ReasonForTrial.50zgt2bmfuk0"),
        title: "删除广告位",
        context: "是否删除此广告位?",
      },
      //检索-table
      filter: { keyword: "" },
      // 表格数据
      tableList: {
        // 表格的列
        columns: [],
        // 表格数据
        list: [],
        options: {
          errortip: "", //空页面提示内容
          mutiSelect: false, //是否显示多选
          issetting: false, //是否可以编辑列
          tableHeight: 0,
        },
      },
      schoolTableConTent: {
        // 表格的列
        columns: [],
        // 表格数据
        list: [],
        options: {
          errortip: "", //空页面提示内容
          mutiSelect: false, //是否显示多选
          issetting: false, //是否可以编辑列
          tableHeight: 500,
        },
      },
      // 分页
      paging: {
        curPage: 1,
        pageSize: 10,
        pageTotal: 0,
      },
      // 表单
      ruleForm: {
        banner_imgurl: "",
        banner_class: "",
        banner_status: "",
        banner_type: "",
        banner_name: "",
        school_id: [],
        banner_sort: "",
      },
      // 表单验证
      rules: {
        banner_name: [
          {
            required: true,
            message: "请输入图片名称",
            trigger: ["change", "blur"],
          },
        ],
        banner_imgurl: [
          {
            required: true,
            message: "请选择图片",
            trigger: ["change", "blur"],
          },
        ],
        banner_sort: [
          {
            required: true,
            message: "请输入排序",
            trigger: ["change", "blur"],
          },
        ],
        banner_type: [
          {
            required: true,
            message: "请选择适用情况",
            trigger: ["change"],
          },
        ],
        school_id: [
          {
            required: true,
            message: "请选择适用园所",
            trigger: ["change"],
          },
        ],
        banner_class: [
          {
            required: true,
            message: "请选择所属模块",
            trigger: ["change", "blur"],
          },
        ],
        banner_status: [
          {
            required: true,
            message: "请选择是否上架",
            trigger: ["change", "blur"],
          },
        ],
      },
      selectedSchoolList: [],
    };
  },
  created() {
    this.Uploadeimg.company_id = this.$Tool.getStorage("COMPANY_ID");
    this.gmcApiUrl = this.$urls.gmcApiUrl;
    this.getTeKidBannerList();
    this.getAllSchoolApi();
  },
  methods: {
    handleColumnChange(k, v, column) {
      if (Number.isNaN(+column.num)) {
        return;
      }
      console.log(k, v, column);
      this.currentAd = column;
      this.getBannerApplyList().then(() => {
        this.suitParkVisible = true;
      });
    },
    handleRemoveFile() {
      this.ruleForm.banner_imgurl = "";
    },
    async getAllSchoolApi() {
      const res = await this.$http.getAllSchoolApi({});
      this.schoolList = res.data.result.list;
    },
    async getBannerApplyList() {
      const res = await setHttp.getBannerApplyList({
        banner_id: this.currentAd.banner_id,
      });
      this.selectedSchoolList = res.data.result.list;
      this.schoolTableConTent.columns = res.data.result.field;
      return new Promise((resolve, reject) => {
        if (res.data.error == 0) {
          this.schoolTableConTent.list = res.data.result.list;
          resolve();
        } else {
          this.schoolTableConTent.list = [];
          this.schoolTableConTent.options.errortip = res.data.errortip;
          reject();
        }
        this.$set(
          this.ruleForm,
          "school_id",
          this.selectedSchoolList.map((item) => item.school_id) || []
        );
      });
    },
    handleAvatarSuccess(res, file) {
      console.log(res, file);
      this.ruleForm.banner_imgurl = res.result.picture_imgurl;
    },
    //园务相关设置 列表
    getTeKidBannerList() {
      setHttp
        .getTeKidBannerList({
          is_count: 1, //是否需要总数，可以不传
          p: this.paging.curPage,
          num: this.paging.pageSize,
          keyword: this.filter.keyword,
        })
        .then((res) => {
          this.paging.pageTotal = parseInt(res.data.result.allnum);
          this.tableList.columns = res.data.result.field;
          if (res.data.error == 0) {
            this.tableList.list = res.data.result.list;
          } else {
            this.tableList.list = [];
            this.tableList.options.errortip = res.data.errortip;
          }
        });
    },
    //检索
    search() {
      this.paging.curPage = 1;
      this.getTeKidBannerList();
    },
    //新增
    handAdd() {
      this.isEdit = false; //是否编辑
      this.cancelVisible = !this.cancelVisible;
      this.resetForm("ruleForm");
    },
    //编辑
    handEdit(v) {
      console.log(v);
      this.currentAd = v;
      this.getBannerApplyList();
      this.banner_id = v.banner_id;
      this.resetForm("ruleForm");
      this.ruleForm = Object.assign({}, v);
      this.isEdit = true;
      this.cancelVisible = !this.cancelVisible;
      // setHttp
      //   .getStuTypesOneApi({
      //     banner_id: this.banner_id,
      //   })
      //   .then((res) => {
      //     let data = res.data.result.list;
      //     this.ruleForm = {
      //       template_title: data.template_title,
      //       template_content: data.template_content,
      //     };
      //     this.isEdit = true;
      //     this.cancelVisible = !this.cancelVisible;
      //   });
    },
    //删除
    handDelete(v) {
      this.banner_id = v.banner_id;
      this.delItem = !this.delItem;
    },
    //删除取消柜询/试听原因
    delTeKidBannerAction() {
      setHttp
        .delTeKidBannerAction({
          banner_id: this.banner_id,
        })
        .then((res) => {
          if (res.data.error == 0) {
            this.$message({ message: res.data.errortip, type: "success" });
            this.delItem = false;
            this.getTeKidBannerList();
          } else {
            this.$message.error(res.data.errortip);
          }
        });
    },
    //侧边弹窗 - 新增 - 提交
    onSubmit() {
      let canSubmit = this.$Tool.isNull("ruleForm", this);
      if (canSubmit) {
        setHttp
          .addTeKidBannerAction({
            banner_imgurl: this.ruleForm.banner_imgurl,
            banner_class: this.ruleForm.banner_class,
            banner_status: this.ruleForm.banner_status,
            banner_type: this.ruleForm.banner_type,
            banner_name: this.ruleForm.banner_name,
            banner_sort: this.ruleForm.banner_sort,
            school_id: JSON.stringify(
              this.ruleForm.school_id.map((item) => ({ school_id: item }))
            ),
          })
          .then((res) => {
            if (res.data.error == 0) {
              this.$message({ message: res.data.errortip, type: "success" });
              this.cancelVisible = false;
              this.getTeKidBannerList();
            } else {
              this.$message.error(res.data.errortip);
            }
          });
      }
    },
    //侧边弹窗 - 编辑 - 提交
    onEditSubmit() {
      let canSubmit = this.$Tool.isNull("ruleForm", this);
      if (canSubmit) {
        setHttp
          .updateTeKidBannerAction({
            banner_id: this.banner_id,
            banner_imgurl: this.ruleForm.banner_imgurl,
            banner_class: this.ruleForm.banner_class,
            banner_status: this.ruleForm.banner_status,
            banner_type: this.ruleForm.banner_type,
            banner_name: this.ruleForm.banner_name,
            banner_sort: this.ruleForm.banner_sort,
            school_id: JSON.stringify(
              this.ruleForm.school_id.map((item) => ({ school_id: item }))
            ),
          })
          .then((res) => {
            if (res.data.error == 0) {
              this.$message({ message: res.data.errortip, type: "success" });
              this.cancelVisible = false;
              this.getTeKidBannerList();
            } else {
              this.$message.error(res.data.errortip);
            }
          });
      }
    },

    // 页码变化
    curPageChange(v) {
      this.paging.curPage = v;
      this.getTeKidBannerList();
    },
    // pageSize改变
    pageSizeChange() {
      this.paging.curPage = 1;
      this.getTeKidBannerList();
    },
    // 重置表单
    resetForm(form) {
      // 数据清空
      this.ruleForm = {
        banner_imgurl: "",
        banner_class: "",
        banner_status: "",
        banner_type: "",
        banner_name: "",
        school_id: [],
        banner_sort: "",
      };
      if (this.$refs[form]) {
        this.$refs[form].resetFields();
      }
    },
    //侧边弹窗-关闭
    handleClose(done) {
      done();
    },
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$refs["auto_height_table"]) {
        this.tableList.options.tableHeight = this.$Tool.getTableHeight(
          this.$refs.auto_height_table.getBoundingClientRect().top + 55
        );
      }
    });
  },
};
</script>

<style lang="less" scoped>
/deep/.el-upload-dragger {
  width: 320px !important;
}
.advertisingSpaceSetting {
}
</style>
